import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:path/path.dart' as path;

import '../AI/tina_dart/BaseAPI.dart';
import '../AI/dify_datasets.dart';
import '../models/user_info.dart';
import '../serve/file_serve.dart';
import '../serve/agent_serve.dart';

class ChatPage extends StatefulWidget {
  final BaseAPI llm;
  final DifyKnowledgeDatabase difyKnowledge;
  final UserInfo userInfo;
  final String appDataDir;
  final FileServe fileServe;
  final String? initialMessage;

  const ChatPage({
    Key? key,
    required this.llm,
    required this.difyKnowledge,
    required this.userInfo,
    required this.appDataDir,
    required this.fileServe,
    this.initialMessage,
  }) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with TickerProviderStateMixin {
  final TextEditingController _messageController = TextEditingController();
  final List<ChatMessage> _messages = [];
  final ScrollController _scrollController = ScrollController();
  final FocusNode _inputFocusNode = FocusNode();
  

  
  bool _isTyping = false;
  bool _isLoading = true;
  late FileServe _fileServe;
  late PatchouliAgentService _agentService;
  String _currentSessionDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
  List<String> _knowledgeCategories = [];
  
  // 添加折叠状态控制
  bool _isHeaderExpanded = false;
  
  // 添加回到底部按钮控制
  bool _showScrollToBottomButton = false;
  
  // 添加聊天会话管理变量
  String? _currentChatFileName; // 当前聊天文件名
  bool _isNewChat = true; // 是否为新聊天
  
  // 添加打字动画控制器
  late AnimationController _typingAnimationController;
  late List<Animation<double>> _typingAnimations;
  
  // 流式更新控制
  Timer? _streamUpdateTimer;

  @override
  void initState() {
    super.initState();
    _fileServe = widget.fileServe;
    
    // 初始化PatchouliAgent
    _agentService = PatchouliAgentService(
      llm: widget.llm,
      difyKnowledge: widget.difyKnowledge,
      fileServe: widget.fileServe,
    );
    
    // 初始化打字动画
    _typingAnimationController = AnimationController(
      duration: Duration(milliseconds: 1200),
      vsync: this,
    );
    
    // 创建三个点的动画，每个点有不同的延迟
    _typingAnimations = List.generate(3, (index) {
      return Tween<double>(begin: 0.3, end: 1.0).animate(
        CurvedAnimation(
          parent: _typingAnimationController,
          curve: Interval(
            index * 0.2, // 每个点延迟0.2
            (index * 0.2) + 0.6, // 动画持续0.6
            curve: Curves.easeInOut,
          ),
        ),
      );
    });
    
    // 监听输入框变化，用于更新发送按钮状态
    _messageController.addListener(() {
      setState(() {
        // 触发重建以更新发送按钮动画
      });
    });
    
    // 监听焦点变化，用于更新输入框边框动画
    _inputFocusNode.addListener(() {
      setState(() {
        // 触发重建以更新输入框边框动画
      });
    });
    
    // 监听滚动位置，控制回到底部按钮显示
    _scrollController.addListener(() {
      final bool isAtBottom = _scrollController.hasClients && 
          _scrollController.offset >= _scrollController.position.maxScrollExtent - 100;
      
      if (_showScrollToBottomButton == isAtBottom) {
        setState(() {
          _showScrollToBottomButton = !isAtBottom;
        });
      }
    });
    
    _initializeChat();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    _inputFocusNode.dispose();
    _typingAnimationController.dispose();
    _streamUpdateTimer?.cancel();
    super.dispose();
  }
  


  Future<void> _initializeChat() async {
    try {
      print('初始化聊天页面...');
      // 获取知识库分类
      print('获取知识库分类...');
      _knowledgeCategories = await _fileServe.getCategories();
      print('获取到${_knowledgeCategories.length}个知识库分类: $_knowledgeCategories');
      
      // 每天第一次进入都显示新聊天，不加载历史记录
      if (!mounted) return;
      
      // 直接显示欢迎消息，开始新聊天
      print('开始新聊天');
      setState(() {
        _messages.add(ChatMessage(
          text: '你好，${widget.userInfo.nickname.isNotEmpty ? widget.userInfo.nickname : '亲爱的用户'}！我是Tina，你的知识管理助手。有什么我能帮到你的吗？',
          isUser: false,
          timestamp: DateTime.now(),
        ));
        _isNewChat = true;
        _currentChatFileName = null;
      });
      
      setState(() {
        _isLoading = false;
      });
      
      // 如果有初始消息，则发送
      if (widget.initialMessage != null && widget.initialMessage!.isNotEmpty) {
        // 添加一个短暂的延迟，确保界面已完全加载
        Future.delayed(Duration(milliseconds: 500), () {
          if (mounted) {
            _sendMessage(widget.initialMessage!);
          }
        });
      }
      
      print('聊天页面初始化完成');
    } catch (e) {
      print('聊天初始化失败: $e');
      if (!mounted) return;
      
      setState(() {
        _isLoading = false;
        _messages.add(ChatMessage(
          text: '初始化聊天失败: $e',
          isUser: false,
          timestamp: DateTime.now(),
        ));
      });
    }
  }
  
  Future<void> _loadChatHistory() async {
    try {
      // 尝试读取今天的聊天历史
      final chatData = await _fileServe.readChatHistory(date: _currentSessionDate);
      if (chatData != null && chatData.containsKey('messages')) {
        print('找到聊天历史，加载中...');
        
        if (!mounted) return;
        
        // 读取消息并解析为ChatMessage对象
        final List<dynamic> messageList = chatData['messages'];
        final parsedMessages = messageList.map((msg) => ChatMessage.fromJson(Map<String, dynamic>.from(msg))).toList();
        
        setState(() {
          _messages.clear();
          _messages.addAll(parsedMessages);
        });
        
        // 滚动到底部
        _scrollToBottom();
        print('聊天历史加载完成，共${parsedMessages.length}条消息');
      } else {
        print('没有找到聊天历史，将显示欢迎消息');
      }
    } catch (e) {
      print('加载聊天历史失败: $e');
    }
  }

  // 开始新对话
  void _startNewChat() {
    setState(() {
      _messages.clear();
      _messages.add(ChatMessage(
        text: '你好，${widget.userInfo.nickname.isNotEmpty ? widget.userInfo.nickname : '亲爱的用户'}！我是Tina，你的知识管理助手。有什么我能帮到你的吗？',
        isUser: false,
        timestamp: DateTime.now(),
      ));
      _currentSessionDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
      
      // 重置聊天会话状态
      _isNewChat = true;
      _currentChatFileName = null;
    });
    
    // 清除Agent的聊天历史
    _agentService.clearChatHistory();
    
    _scrollToBottom();
    
    // 显示新聊天开始提示
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('已开始新的聊天会话'),
        backgroundColor: Color(0xFF667eea),
      ),
    );
  }
  
  // 加载历史聊天记录
  Future<void> _showHistoryDialog() async {
    // 获取聊天历史文件列表
    final chatFiles = await _fileServe.listChatHistoryFiles();
    if (chatFiles.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('没有找到历史聊天记录')),
      );
      return;
    }
    
    // 显示对话框
    if (!mounted) return;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.history, color: Color(0xFF667eea)),
            SizedBox(width: 8),
            Text('历史对话', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600)),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          height: 400, // 增加高度
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: chatFiles.length,
            itemBuilder: (context, index) {
              final fileName = path.basename(chatFiles[index]);
              final chatInfo = _parseChatFileName(fileName);
              
              return Card(
                margin: EdgeInsets.symmetric(vertical: 4),
                elevation: 2,
                child: ListTile(
                  leading: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      gradient: LinearGradient(
                        colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                      ),
                    ),
                    child: Icon(Icons.chat_bubble_outline, color: Colors.white, size: 20),
                  ),
                  title: Text(
                    chatInfo['title']!,
                    style: TextStyle(
                      fontSize: 15,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey[800],
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(height: 4),
                      Text(
                        chatInfo['date']!,
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.grey[600],
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      if (fileName == _currentChatFileName)
                        Container(
                          margin: EdgeInsets.only(top: 4),
                          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                          decoration: BoxDecoration(
                            color: Color(0xFF667eea).withOpacity(0.1),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            '当前会话',
                            style: TextStyle(
                              fontSize: 11,
                              color: Color(0xFF667eea),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                    ],
                  ),
                  trailing: Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
                  onTap: () async {
                    Navigator.of(context).pop();
                    await _loadHistoryChatFromFile(fileName);
                  },
                ),
              );
            },
          ),
        ),
        actions: [
          TextButton(
            child: Text('取消', style: TextStyle(color: Colors.grey[600])),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  }
  
  // 搜索消息对话框
  void _showSearchDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('搜索消息'),
        content: Text('消息搜索功能正在开发中'),
        actions: [
          TextButton(
            child: Text('确定'),
            onPressed: () => Navigator.of(context).pop(),
          ),
        ],
      ),
    );
  }

  // 新对话确认对话框
  void _showNewChatDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('开始新对话'),
        content: Text('确定要开始一个新的对话吗？当前对话已保存。'),
        actions: [
          TextButton(
            child: Text('取消'),
            onPressed: () => Navigator.of(context).pop(),
          ),
          TextButton(
            child: Text('确定'),
            onPressed: () {
              Navigator.of(context).pop();
              _startNewChat();
            },
          ),
        ],
      ),
    );
  }

  // 清空聊天确认对话框
  void _showClearChatDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('清空聊天记录'),
        content: Text('确定要清空当前所有聊天记录吗？此操作不可撤销。'),
        actions: [
          TextButton(
            child: Text('取消'),
            onPressed: () => Navigator.of(context).pop(),
          ),
          TextButton(
            child: Text('确定'),
            onPressed: () {
              Navigator.of(context).pop();
              setState(() {
                _messages.clear();
                _messages.add(ChatMessage(
                  text: 'Tina已清空聊天记录。有什么我能帮到你的吗？',
                  isUser: false,
                  timestamp: DateTime.now(),
                ));
              });
              // 清除Agent的聊天历史
              _agentService.clearChatHistory();
            },
          ),
        ],
      ),
    );
  }

  // 导出聊天记录
  void _exportChatHistory() {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('导出功能正在开发中')),
    );
  }

  // 显示附件选项
  void _showAttachmentOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: Icon(Icons.photo),
              title: Text('选择图片'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('图片上传功能正在开发中')),
                );
              },
            ),
            ListTile(
              leading: Icon(Icons.insert_drive_file),
              title: Text('选择文件'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('文件上传功能正在开发中')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }
  
  // 加载特定日期的聊天记录
  Future<void> _loadHistoryChat(String date) async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      final chatData = await _fileServe.readChatHistory(date: date);
      if (chatData != null && chatData.containsKey('messages')) {
        final List<dynamic> messageList = chatData['messages'];
        final parsedMessages = messageList.map((msg) => ChatMessage.fromJson(Map<String, dynamic>.from(msg))).toList();
        
        setState(() {
          _messages.clear();
          _messages.addAll(parsedMessages);
          _currentSessionDate = date;
        });
        
        // 清除并重建Agent的聊天历史
        _agentService.clearChatHistory();
        
        _scrollToBottom();
        print('加载${date}的聊天历史，共${parsedMessages.length}条消息');
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('无法加载${date}的聊天记录')),
        );
      }
    } catch (e) {
      print('加载历史聊天记录失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载历史聊天记录失败: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _scrollToBottom() {
    // 直接跳转到底部，不使用动画
    if (_scrollController.hasClients && mounted) {
      _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
    }
  }

  // 保存聊天记录到自定义文件名
  Future<void> _saveChatToCustomFile(String fileName, Map<String, dynamic> chatData) async {
    try {
      final chatDir = Directory(path.join(_fileServe.appDataDir, 'chat'));
      if (!await chatDir.exists()) {
        await chatDir.create(recursive: true);
      }
      
      final chatFile = File(path.join(chatDir.path, fileName));
      await chatFile.writeAsString(jsonEncode(chatData));
    } catch (e) {
      print('保存自定义聊天文件失败: $e');
      throw e;
    }
  }

  // 解析聊天文件名，提取标题和日期
  Map<String, String> _parseChatFileName(String fileName) {
    try {
      // 移除.json扩展名
      final nameWithoutExtension = fileName.replaceAll('.json', '');
      
      // 检查是否是新格式：日期_内容.json
      if (nameWithoutExtension.contains('_')) {
        final parts = nameWithoutExtension.split('_');
        if (parts.length >= 2) {
          final date = parts[0];
          final title = parts.sublist(1).join('_'); // 处理标题中可能有下划线的情况
          
          // 验证日期格式
          try {
            DateFormat('yyyy-MM-dd').parse(date);
            return {
              'title': title.isEmpty ? '无标题聊天' : title,
              'date': date,
            };
          } catch (e) {
            // 日期解析失败，可能是旧格式
          }
        }
      }
      
      // 旧格式或解析失败，直接使用文件名作为日期
      return {
        'title': '历史聊天',
        'date': nameWithoutExtension,
      };
    } catch (e) {
      print('解析文件名失败: $e');
      return {
        'title': '未知聊天',
        'date': fileName,
      };
    }
  }

  // 从指定文件加载历史聊天
  Future<void> _loadHistoryChatFromFile(String fileName) async {
    try {
      setState(() {
        _isLoading = true;
      });
      
      // 直接读取指定文件
      final chatDir = Directory(path.join(_fileServe.appDataDir, 'chat'));
      final chatFile = File(path.join(chatDir.path, fileName));
      
      if (await chatFile.exists()) {
        final content = await chatFile.readAsString();
        final chatData = jsonDecode(content) as Map<String, dynamic>;
        
        if (chatData.containsKey('messages')) {
          final List<dynamic> messageList = chatData['messages'];
          final parsedMessages = messageList.map((msg) => ChatMessage.fromJson(Map<String, dynamic>.from(msg))).toList();
          
          setState(() {
            _messages.clear();
            _messages.addAll(parsedMessages);
            _currentChatFileName = fileName;
            _isNewChat = false; // 设置为非新聊天
            
            // 从文件名提取日期用于兼容性
            final chatInfo = _parseChatFileName(fileName);
            _currentSessionDate = chatInfo['date']!;
          });
          
          // 清除并重建Agent的聊天历史
          _agentService.clearChatHistory();
          
          _scrollToBottom();
          print('加载历史聊天文件: $fileName，共${parsedMessages.length}条消息');
          
          // 显示加载成功提示
          final chatInfo = _parseChatFileName(fileName);
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('已加载聊天：${chatInfo['title']}'),
              backgroundColor: Color(0xFF667eea),
            ),
          );
        } else {
          throw Exception('文件格式不正确');
        }
      } else {
        throw Exception('文件不存在');
      }
    } catch (e) {
      print('加载历史聊天文件失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('加载聊天记录失败: $e')),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _sendMessage(String message) async {
    if (message.trim().isEmpty) return;
    
    if (!mounted) return;
    
    setState(() {
      _messages.add(ChatMessage(
        text: message,
        isUser: true,
        timestamp: DateTime.now(),
      ));
      _messageController.clear();
      _isTyping = true;
    });

    // 延迟滚动，让新消息动画完成
    Future.delayed(Duration(milliseconds: 100), () {
      _scrollToBottom();
    });

    try {
      print('发送消息: $message');
      
      // 开始打字动画
      _typingAnimationController.repeat();
      
      // 创建接收LLM消息的ChatMessage对象
      final botMessage = ChatMessage(
        text: '',
        isUser: false,
        timestamp: DateTime.now(),
        toolCalls: <ToolCallInfo>[],
      );
      
      setState(() {
        _messages.add(botMessage);
      });

      // 工具调用跟踪
      final Map<String, ToolCallInfo> pendingToolCalls = {};
      String? currentToolName;
      String? currentToolArgs;

      // 使用Agent的流式聊天
      await for (final response in _agentService.chatStream(message)) {
        if (!mounted) break;
        
        // 只处理助手角色的响应内容，过滤掉工具调用结果
        if (response.content.isNotEmpty && response.role == 'assistant') {
          setState(() {
            botMessage.text += response.content;
          });
          
          // 批量处理UI更新
          _streamUpdateTimer?.cancel();
          _streamUpdateTimer = Timer(Duration(milliseconds: 50), () {
            if (mounted && _scrollController.hasClients) {
              _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
            }
          });
        }
        
        // 处理工具调用信息
        if (response.toolName != null) {
          currentToolName = response.toolName;
          print('正在调用工具: ${response.toolName}');
        }
        
        if (response.toolArguments != null) {
          currentToolArgs = response.toolArguments;
          print('工具参数: ${response.toolArguments}');
          
          // 如果有工具名称和参数，创建工具调用信息
          if (currentToolName != null) {
            final toolCallKey = '${currentToolName}_${DateTime.now().millisecondsSinceEpoch}';
            pendingToolCalls[toolCallKey] = ToolCallInfo(
              name: currentToolName!,
              arguments: currentToolArgs!,
              result: '',
              isCompleted: false,
            );
            
            // 更新UI显示工具调用
            setState(() {
              botMessage.toolCalls.add(pendingToolCalls[toolCallKey]!);
            });
          }
        }
        
        // 处理工具结果
        if (response.role == 'tool' && response.content.isNotEmpty) {
          print('工具结果: ${response.content}');
          
          // 更新最新的工具调用结果
          if (pendingToolCalls.isNotEmpty) {
            final latestKey = pendingToolCalls.keys.last;
            final updatedToolCall = ToolCallInfo(
              name: pendingToolCalls[latestKey]!.name,
              arguments: pendingToolCalls[latestKey]!.arguments,
              result: response.content,
              isCompleted: true,
            );
            
            pendingToolCalls[latestKey] = updatedToolCall;
            
            // 更新UI中的工具调用结果
            setState(() {
              final index = botMessage.toolCalls.indexWhere((call) => 
                call.name == updatedToolCall.name && !call.isCompleted);
              if (index != -1) {
                botMessage.toolCalls[index] = updatedToolCall;
              }
            });
          }
        }
        
        // 处理推理内容
        if (response.reasoningContent != null) {
          print('推理内容: ${response.reasoningContent}');
        }
      }
      
    } catch (e) {
      print('发送消息失败: $e');
      setState(() {
        _messages.add(ChatMessage(
          text: '抱歉，发生了错误：$e',
          isUser: false,
          timestamp: DateTime.now(),
        ));
      });
    } finally {
      if (mounted) {
        setState(() {
          _isTyping = false;
          // 停止打字动画
          _typingAnimationController.stop();
          _typingAnimationController.reset();
        });
      }
      
      // 延迟滚动，让新消息动画完成
      Future.delayed(Duration(milliseconds: 100), () {
        _scrollToBottom();
      });
      
      // 保存聊天记录
      try {
        final chatData = {
          'messages': _messages.map((msg) => msg.toJson()).toList(),
          'time': DateTime.now().toIso8601String(),
        };
        
        // 如果是新聊天且这是用户的第一句话，生成新的文件名
        if (_isNewChat && _currentChatFileName == null) {
          final dateStr = DateFormat('yyyy-MM-dd').format(DateTime.now());
          final userMessage = message.trim();
          // 清理用户消息，只保留前15个字符作为文件名的一部分
          final cleanMessage = userMessage
              .replaceAll(RegExp(r'[^\u4e00-\u9fa5a-zA-Z0-9]'), '') // 只保留中文、英文和数字
              .substring(0, userMessage.length > 15 ? 15 : userMessage.length);
          
          _currentChatFileName = '${dateStr}_${cleanMessage}.json';
          _isNewChat = false;
          print('创建新聊天文件: $_currentChatFileName');
        }
        
        // 保存聊天记录到自定义文件名
        if (_currentChatFileName != null) {
          await _saveChatToCustomFile(_currentChatFileName!, chatData);
          print('聊天历史保存成功: $_currentChatFileName');
        }
      } catch (e) {
        print('保存聊天历史失败: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    return Scaffold(
      backgroundColor: Colors.white, // 改为白色背景
      body: Column(
          children: [
          // 美化的顶部区域
          _buildBeautifulHeader(),
          // 聊天内容区域
          Expanded(
            child: _isLoading 
                ? _buildLoadingScreen()
                : _buildChatContent(),
          ),
        ],
      ),
    );
  }

  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.fromLTRB(20, 8, 20, 20),
          child: Column(
            children: [
              // 顶部导航栏
              Row(
                children: [
                  // 返回按钮
            Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: IconButton(
                      icon: Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                  SizedBox(width: 12),
                  
                  // 头像和信息
                  Container(
                    padding: EdgeInsets.all(2),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      shape: BoxShape.circle,
                    ),
                    child: Container(
                      width: 40,
                      height: 40,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                          colors: [Colors.purple[300]!.withOpacity(0.8), Colors.purple[500]!.withOpacity(0.8)],
                ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.2),
                            blurRadius: 6,
                            offset: Offset(0, 3),
                          ),
                        ],
              ),
              child: Center(
                        child: ClipOval(
                child: Image.asset(
                  'assets/images/patchouli.png',
                  errorBuilder: (context, error, stackTrace) => Text(
                    'T',
                    style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
                  ),
                  width: 20,
                  height: 20,
                            fit: BoxFit.cover,
                ),
              ),
            ),
                    ),
                  ),
                  
            SizedBox(width: 12),
                  
                  // 名称和状态
                  Expanded(
                    child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Tina',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                            letterSpacing: 0.3,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                        SizedBox(height: 2),
                        Row(
                          children: [
                            Container(
                              width: 6,
                              height: 6,
                              decoration: BoxDecoration(
                                color: _isTyping ? Colors.green : Colors.white.withOpacity(0.8),
                                shape: BoxShape.circle,
                                boxShadow: [
                                  BoxShadow(
                                    color: _isTyping ? Colors.green.withOpacity(0.5) : Colors.white.withOpacity(0.3),
                                    blurRadius: 2,
                                    spreadRadius: 0.5,
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 6),
                            Flexible(
                              child: Text(
                                _isTyping ? '正在思考...' : '智能助手',
                  style: TextStyle(
                    fontSize: 12,
                                  color: Colors.white.withOpacity(0.9),
                                  fontWeight: FontWeight.w500,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ],
        ),
                  ),
                  
                  // 功能按钮组
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildHeaderButton(Icons.search, '搜索', _showSearchDialog),
                      SizedBox(width: 4),
                      _buildHeaderButton(Icons.history, '历史', _showHistoryDialog),
                      SizedBox(width: 4),
                      // 添加展开/折叠按钮
                      _buildHeaderButton(
                        _isHeaderExpanded ? Icons.expand_less : Icons.expand_more, 
                        _isHeaderExpanded ? '收起' : '展开', 
                        () => setState(() => _isHeaderExpanded = !_isHeaderExpanded)
                      ),
                      SizedBox(width: 4),
                      _buildHeaderMenuButton(),
                    ],
                  ),
                ],
              ),
              
              // 聊天统计信息 - 添加动画展开/收起
              AnimatedContainer(
                duration: Duration(milliseconds: 300),
                curve: Curves.easeInOut,
                height: _isHeaderExpanded ? null : 0,
                child: _isHeaderExpanded ? Column(
                  children: [
                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(16),
                        border: Border.all(color: Colors.white.withOpacity(0.2)),
                      ),
                      child: IntrinsicHeight(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Expanded(child: _buildStatItem('对话', '${_messages.length}', Icons.chat_bubble_outline)),
                            Container(width: 1, color: Colors.white.withOpacity(0.3)),
                            Expanded(child: _buildStatItem('知识库', '${_knowledgeCategories.length}', Icons.library_books)),
                            Container(width: 1, color: Colors.white.withOpacity(0.3)),
                            Expanded(child: _buildStatItem('今日', DateFormat('MM-dd').format(DateTime.now()), Icons.calendar_today)),
                          ],
                        ),
                      ),
                    ),
                  ],
                ) : null,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeaderButton(IconData icon, String tooltip, VoidCallback onPressed) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(8),
      ),
      child: IconButton(
        icon: Icon(icon, color: Colors.white, size: 18),
        iconSize: 18,
        constraints: BoxConstraints(minWidth: 32, minHeight: 32),
        padding: EdgeInsets.zero,
        tooltip: tooltip,
        onPressed: onPressed,
      ),
    );
  }

  Widget _buildHeaderMenuButton() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(8),
          ),
      child: PopupMenuButton<String>(
        icon: Icon(Icons.more_vert, color: Colors.white, size: 18),
        iconSize: 18,
        constraints: BoxConstraints(minWidth: 32, minHeight: 32),
        padding: EdgeInsets.zero,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        color: Colors.white,
            onSelected: (value) {
              switch (value) {
                case 'new_chat':
                  _showNewChatDialog();
                  break;
                case 'clear_chat':
                  _showClearChatDialog();
                  break;
                case 'export_chat':
                  _exportChatHistory();
                  break;
              }
            },
            itemBuilder: (context) => [
          _buildPopupMenuItem('new_chat', Icons.add, '新对话'),
          _buildPopupMenuItem('clear_chat', Icons.delete_outline, '清空记录'),
          _buildPopupMenuItem('export_chat', Icons.download, '导出聊天'),
                  ],
                ),
    );
  }

  PopupMenuItem<String> _buildPopupMenuItem(String value, IconData icon, String text) {
    return PopupMenuItem(
      value: value,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 4),
                child: Row(
                  children: [
            Container(
              padding: EdgeInsets.all(6),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                ),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Icon(icon, size: 16, color: Color(0xFF667eea)),
            ),
            SizedBox(width: 12),
            Text(
              text,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: Colors.grey[700],
              ),
            ),
                  ],
                ),
              ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      mainAxisSize: MainAxisSize.min,
                  children: [
        Icon(icon, color: Colors.white, size: 14),
        SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontSize: 13,
            fontWeight: FontWeight.w700,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.8),
            fontSize: 10,
            fontWeight: FontWeight.w500,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          ),
        ],
    );
  }

  Widget _buildLoadingScreen() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey[50],
      ),
      child: Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                ),
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 20,
                    offset: Offset(0, 10),
                  ),
                ],
              ),
              child: Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  strokeWidth: 3,
                ),
              ),
                              ),
            SizedBox(height: 24),
                              Text(
                    '正在初始化聊天...',
              style: TextStyle(
                color: Colors.grey[600],
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 8),
            Text(
                              'Tina正在准备为您服务',
              style: TextStyle(
                color: Colors.grey[500],
                fontSize: 14,
              ),
                              ),
                            ],
                          ),
      ),
    );
  }

  Widget _buildChatContent() {
    return Column(
      children: [
        Expanded(
          child: Stack(
            children: [
              // 主要聊天内容
              _messages.isEmpty
                  ? _buildEmptyState()
                  : ListView.builder(
                      controller: _scrollController,
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                      itemCount: _messages.length,
                      physics: BouncingScrollPhysics(),
                      cacheExtent: 200,
                      addAutomaticKeepAlives: false,
                      addRepaintBoundaries: true,
                      itemBuilder: (context, index) {
                        final message = _messages[index];
                        final isLastMessage = index == _messages.length - 1;
                        final isStreamingMessage = isLastMessage && !message.isUser && _isTyping;
                        
                        if (isStreamingMessage) {
                          return ChatBubble(
                            key: ValueKey('streaming_${message.timestamp.millisecondsSinceEpoch}'),
                            message: message,
                            fileServe: _fileServe,
                          );
                        }
                        
                        final isNewMessage = isLastMessage && !message.isUser && !_isTyping;
                        return TweenAnimationBuilder<double>(
                          duration: Duration(milliseconds: isNewMessage ? 300 : 0),
                          tween: Tween<double>(begin: isNewMessage ? 0.0 : 1.0, end: 1.0),
                          curve: Curves.easeOutCubic,
                          builder: (context, opacityValue, child) {
                            return Opacity(
                              opacity: opacityValue,
                              child: ChatBubble(
                                key: ValueKey('message_${message.timestamp.millisecondsSinceEpoch}_${message.isUser}'),
                                message: message,
                                fileServe: _fileServe,
                              ),
                            );
                          },
                        );
                      },
                    ),
              
              // 回到底部按钮
              if (_showScrollToBottomButton)
                Positioned(
                  right: 16,
                  bottom: 80, // 调整位置，避免与输入区域重叠
                  child: _buildScrollToBottomButton(),
                ),
            ],
          ),
        ),
        if (_isTyping) _buildTypingIndicator(),
        _buildInputArea(),
      ],
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: EdgeInsets.all(32),
      child: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
                      children: [
            // 美化的头像区域
          Container(
              width: 140,
              height: 140,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              gradient: LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                ),
                boxShadow: [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 30,
                    offset: Offset(0, 15),
                  ),
                ],
              ),
              child: Container(
                margin: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
            ),
            child: Center(
                  child: ClipOval(
                child: Image.asset(
                  'assets/images/patchouli.png',
                  errorBuilder: (context, error, stackTrace) => Icon(
                    Icons.chat_bubble_outline,
                    size: 60,
                    color: Color(0xFF667eea),
                  ),
                  width: 80,
                  height: 80,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
            ),
            
            SizedBox(height: 32),
            
            // 欢迎文本
          Text(
                            '开始与Tina聊天吧',
            style: TextStyle(
                fontSize: 24,
                fontWeight: FontWeight.w700,
                color: Colors.grey[800],
                letterSpacing: 0.5,
            ),
          ),
            
            SizedBox(height: 12),
            
            Container(
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 8),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                ),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
            '我可以帮你搜索知识库、回答问题',
            style: TextStyle(
                  fontSize: 15,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
            
            SizedBox(height: 40),
            
            // 快捷回复按钮
            Column(
              children: [
                Text(
                  '试试这些问题：',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey[700],
            ),
          ),
                SizedBox(height: 16),
          Wrap(
                  spacing: 12,
                  runSpacing: 12,
                  alignment: WrapAlignment.center,
            children: [
                    _buildQuickReplyChip('📚 搜索文档'),
                    _buildQuickReplyChip('🆕 最新知识'),
                    _buildQuickReplyChip('❓ 使用帮助'),
                    _buildQuickReplyChip('🏷️ 查看标签'),
            ],
          ),
        ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildQuickReplyChip(String text) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
        ),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: Color(0xFF667eea).withOpacity(0.3)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: () => _sendMessage(text.replaceAll(RegExp(r'[📚🆕❓🏷️]\s*'), '')),
          borderRadius: BorderRadius.circular(20),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Text(
              text,
              style: TextStyle(
                color: Color(0xFF667eea),
                fontSize: 14,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildTypingIndicator() {
    // 启动打字动画
    if (!_typingAnimationController.isAnimating) {
      _typingAnimationController.repeat();
    }
    
    return AnimatedSlide(
      offset: Offset(0, 0),
      duration: Duration(milliseconds: 300),
      curve: Curves.easeOutCubic,
      child: AnimatedOpacity(
        opacity: 1.0,
        duration: Duration(milliseconds: 300),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: Row(
            children: [
              // 美化的头像
              Container(
                width: 36,
                height: 36,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: LinearGradient(
                    colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0xFF667eea).withOpacity(0.3),
                      blurRadius: 8,
                      offset: Offset(0, 4),
                    ),
                  ],
                  ),
                child: Container(
                  margin: EdgeInsets.all(2),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.white,
                ),
                child: Center(
                    child: ClipOval(
                  child: Image.asset(
                    'assets/images/patchouli.png',
                    errorBuilder: (context, error, stackTrace) => Text(
                      'T',
                          style: TextStyle(color: Color(0xFF667eea), fontSize: 12, fontWeight: FontWeight.bold),
                    ),
                    width: 16,
                    height: 16,
                        fit: BoxFit.cover,
                  ),
                ),
              ),
                ),
              ),
              
              SizedBox(width: 12),
              
              // 美化的打字气泡
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
                  ),
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20),
                    bottomRight: Radius.circular(20),
                    bottomLeft: Radius.circular(4),
                  ),
                  border: Border.all(color: Color(0xFF667eea).withOpacity(0.1)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.05),
                      blurRadius: 8,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.chat_bubble_outline,
                      size: 14,
                      color: Color(0xFF667eea).withOpacity(0.6),
                    ),
                    SizedBox(width: 8),
                    ...List.generate(3, (index) => 
                    Padding(
                      padding: EdgeInsets.only(right: index < 2 ? 4 : 0),
                      child: _buildTypingDot(index),
                    ),
                  ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTypingDot(int index) {
    return AnimatedBuilder(
      animation: _typingAnimations[index],
      builder: (context, child) {
        return Transform.scale(
          scale: 0.8 + (_typingAnimations[index].value * 0.4),
          child: Container(
            width: 6,
            height: 6,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              gradient: LinearGradient(
                colors: [
                  Color(0xFF667eea).withOpacity(_typingAnimations[index].value * 0.8),
                  Color(0xFF764ba2).withOpacity(_typingAnimations[index].value * 0.8),
                ],
              ),
              boxShadow: [
                BoxShadow(
                  color: Color(0xFF667eea).withOpacity(_typingAnimations[index].value * 0.3),
                  blurRadius: 4,
                  spreadRadius: 1,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildInputArea() {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        child: Row(
          children: [
            // 附件按钮 - 去掉所有背景装饰
            IconButton(
              icon: Icon(Icons.attach_file, color: Color(0xFF667eea), size: 20),
              constraints: BoxConstraints(minWidth: 40, minHeight: 40),
              onPressed: _showAttachmentOptions,
            ),
            
            SizedBox(width: 10),
            
            // 输入框 - 最大3行，超过部分隐藏
            Expanded(
              child: TextField(
                controller: _messageController,
                focusNode: _inputFocusNode,
                decoration: InputDecoration(
                  hintText: '💭 输入消息...',
                  hintStyle: TextStyle(
                    color: Colors.grey[500], 
                    fontSize: 15,
                    fontWeight: FontWeight.w400,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(22),
                    borderSide: BorderSide(color: Colors.grey[300]!, width: 1),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(22),
                    borderSide: BorderSide(color: Colors.grey[300]!, width: 1),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(22),
                    borderSide: BorderSide(color: Color(0xFF667eea), width: 2),
                  ),
                  filled: false, // 确保没有背景填充
                  contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                ),
                onSubmitted: _sendMessage,
                maxLines: 3, // 最大3行
                minLines: 1, // 最小1行
                textInputAction: TextInputAction.send,
                style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.w500,
                  color: Colors.grey[800],
                ),
              ),
            ),
            
            SizedBox(width: 10),
            
            // 发送按钮
            AnimatedScale(
              scale: _messageController.text.trim().isNotEmpty ? 1.0 : 0.9,
              duration: Duration(milliseconds: 200),
              curve: Curves.easeOutCubic,
              child: Container(
                width: 44,
                height: 44,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: LinearGradient(
                    colors: _messageController.text.trim().isNotEmpty 
                        ? [Color(0xFF667eea), Color(0xFF764ba2)]
                        : [Colors.grey[300]!, Colors.grey[400]!],
                  ),
                  boxShadow: _messageController.text.trim().isNotEmpty ? [
                    BoxShadow(
                      color: Color(0xFF667eea).withOpacity(0.3),
                      blurRadius: 8,
                      offset: Offset(0, 4),
                    ),
                  ] : [],
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    borderRadius: BorderRadius.circular(22),
                    onTap: _messageController.text.trim().isNotEmpty 
                      ? () => _sendMessage(_messageController.text.trim())
                      : null,
                    child: Center(
                      child: Icon(
                        Icons.send_rounded, 
                        color: Colors.white, 
                        size: 18,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildScrollToBottomButton() {
    return AnimatedScale(
      scale: _showScrollToBottomButton ? 1.0 : 0.0,
      duration: Duration(milliseconds: 200),
      curve: Curves.easeOutCubic,
      child: Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          gradient: LinearGradient(
            colors: [Color(0xFF667eea), Color(0xFF764ba2)],
          ),
          boxShadow: [
            BoxShadow(
              color: Color(0xFF667eea).withOpacity(0.3),
              blurRadius: 12,
              offset: Offset(0, 6),
            ),
          ],
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            borderRadius: BorderRadius.circular(24),
            onTap: _scrollToBottom,
            child: Center(
              child: Icon(
                Icons.keyboard_arrow_down_rounded,
                color: Colors.white,
                size: 24,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class ChatBubble extends StatelessWidget {
  final ChatMessage message;
  final FileServe? fileServe;

  const ChatBubble({
    Key? key,
    required this.message,
    this.fileServe,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    // 移除调试输出以提升性能
    
    // 直接返回内容，不使用复杂动画
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6.0),
      child: _buildChatContent(context, isDark),
    );
  }

  Widget _buildChatContent(BuildContext context, bool isDark) {
    return Row(
      mainAxisAlignment: message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
        if (!message.isUser) ...[
          _buildAvatar(isDark),
          SizedBox(width: 12),
        ],
        Flexible(
          child: Column(
            crossAxisAlignment: message.isUser ? CrossAxisAlignment.end : CrossAxisAlignment.start,
            children: [
              // 工具调用组件显示在气泡上方
              if (message.toolCalls.isNotEmpty)
                _buildToolCallsWidget(context),
              _buildMessageBubble(context, isDark),
              SizedBox(height: 6),
              _buildMessageFooter(context),
            ],
          ),
        ),
        if (message.isUser) ...[
          SizedBox(width: 12),
          _buildUserAvatar(),
        ],
      ],
    );
  }

  Widget _buildAvatar(bool isDark) {
    return Container(
      width: 36,
      height: 36,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          colors: [Colors.purple[300]!, Colors.purple[500]!],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.purple.withOpacity(0.3),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Center(
              child: Image.asset(
                'assets/images/patchouli.png',
          errorBuilder: (context, error, stackTrace) => Text(
            'T',
            style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold),
          ),
          width: 24,
          height: 24,
        ),
      ),
    );
  }

  Widget _buildUserAvatar() {
    return FutureBuilder<String?>(
      future: fileServe?.getUserAvatarPath(),
      builder: (context, snapshot) {
        return Container(
          width: 36,
          height: 36,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: snapshot.hasData && snapshot.data != null
                ? null
                : LinearGradient(
                    colors: [Colors.blue[400]!, Colors.blue[600]!],
                  ),
            boxShadow: [
              BoxShadow(
                color: Colors.blue.withOpacity(0.3),
                blurRadius: 8,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: ClipOval(
            child: snapshot.hasData && snapshot.data != null
                ? Image.file(
                    File(snapshot.data!),
                    fit: BoxFit.cover,
                    width: 36,
                    height: 36,
                    errorBuilder: (context, error, stackTrace) {
                      return Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Colors.blue[400]!, Colors.blue[600]!],
                          ),
                        ),
                        child: Center(
                          child: Text(
                            '我',
                            style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                              fontSize: 14,
                            ),
                          ),
                        ),
                      );
                    },
                  )
                : Center(
                    child: Text(
                      '我',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                        fontSize: 14,
                      ),
                    ),
                  ),
          ),
        );
      },
    );
  }

  Widget _buildMessageBubble(BuildContext context, bool isDark) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.75,
      ),
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  decoration: BoxDecoration(
        gradient: message.isUser 
          ? LinearGradient(
              colors: [Colors.blue[400]!, Colors.blue[600]!],
            )
          : null,
        color: message.isUser 
          ? null 
          : (isDark ? Colors.grey[800] : Colors.white),
                    borderRadius: BorderRadius.only(
          topLeft: Radius.circular(message.isUser ? 20 : 8),
          topRight: Radius.circular(message.isUser ? 8 : 20),
          bottomLeft: Radius.circular(20),
          bottomRight: Radius.circular(20),
                    ),
                    boxShadow: [
                      BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 8,
            offset: Offset(0, 2),
                      ),
                    ],
                  ),
                  child: _buildMessageContent(context),
    );
  }

  Widget _buildMessageFooter(BuildContext context) {
    return Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
          DateFormat('HH:mm').format(message.timestamp),
                      style: TextStyle(
            fontSize: 11,
            color: Colors.grey[500],
            fontWeight: FontWeight.w500,
                      ),
                    ),
        if (!message.isUser) ...[
          SizedBox(width: 8),
                      InkWell(
                        onTap: () {
              Clipboard.setData(ClipboardData(text: message.text));
                          ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(
                  content: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(Icons.check, color: Colors.white, size: 16),
                      SizedBox(width: 8),
                      Text('已复制到剪贴板'),
                    ],
                  ),
                  duration: Duration(seconds: 2),
                  backgroundColor: Colors.green,
                  behavior: SnackBarBehavior.floating,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                            ),
                          );
                        },
            borderRadius: BorderRadius.circular(12),
            child: Container(
              padding: EdgeInsets.all(4),
                        child: Icon(
                          Icons.copy,
                          size: 14,
                color: Colors.grey[500],
              ),
            ),
          ),
        ],
      ],
    );
  }
  
  Widget _buildMessageContent(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    // 移除调试输出以提升性能
    
    try {
      // 简单区分是否可能是Markdown内容
      final containsMarkdown = message.text.contains('#') || 
                              message.text.contains('*') || 
                              message.text.contains('```') || 
                              message.text.contains('- ');
      
      if (containsMarkdown && !message.isUser) {
        return MarkdownBody(
          data: message.text,
          selectable: true,
          styleSheet: MarkdownStyleSheet(
            p: TextStyle(
              fontSize: 15,
              color: isDark ? Colors.white : Colors.black87,
              height: 1.5,
            ),
            h1: TextStyle(
              fontSize: 22, 
              fontWeight: FontWeight.bold,
              color: isDark ? Colors.white : Colors.black87,
            ),
            h2: TextStyle(
              fontSize: 20, 
              fontWeight: FontWeight.bold,
              color: isDark ? Colors.white : Colors.black87,
            ),
            h3: TextStyle(
              fontSize: 18, 
              fontWeight: FontWeight.bold,
              color: isDark ? Colors.white : Colors.black87,
            ),
            code: TextStyle(
              backgroundColor: isDark ? Colors.grey[700] : Colors.grey[200],
              color: isDark ? Colors.green[300] : Colors.green[700],
              fontFamily: 'monospace',
              fontSize: 14,
            ),
            codeblockDecoration: BoxDecoration(
              color: isDark ? Colors.grey[800] : Colors.grey[100],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(
                color: isDark ? Colors.grey[600]! : Colors.grey[300]!,
              ),
            ),
            blockquoteDecoration: BoxDecoration(
              color: isDark ? Colors.grey[800] : Colors.grey[50],
              borderRadius: BorderRadius.circular(4),
              border: Border(
                left: BorderSide(
                  color: Colors.purple[400]!,
                  width: 4,
                ),
              ),
            ),
          ),
        );
      } else {
        return SelectableText(
          message.text,
          style: TextStyle(
            fontSize: 15,
            color: message.isUser 
              ? Colors.white 
              : (isDark ? Colors.white : Colors.black87),
            height: 1.4,
          ),
        );
      }
    } catch (e) {
      print('渲染消息内容失败: $e');
      return Text(
        message.text,
        style: TextStyle(
          color: message.isUser 
            ? Colors.white 
            : (isDark ? Colors.white : Colors.black87),
        ),
      );
    }
  }

  Widget _buildToolCallsWidget(BuildContext context) {
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;
    
    return Container(
      margin: EdgeInsets.only(bottom: 8),
      constraints: BoxConstraints(
        maxWidth: MediaQuery.of(context).size.width * 0.75,
      ),
      child: Column(
        children: message.toolCalls.map((toolCall) => 
          Container(
            margin: EdgeInsets.only(bottom: 4),
            decoration: BoxDecoration(
              color: _isMemoryTool(toolCall.name)
                ? (isDark ? Colors.purple[900]!.withOpacity(0.3) : Colors.purple[50]!.withOpacity(0.8))
                : (isDark ? Colors.grey[800]!.withOpacity(0.7) : Colors.blue[50]!.withOpacity(0.8)),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: _isMemoryTool(toolCall.name)
                  ? (toolCall.isCompleted 
                    ? Colors.purple.withOpacity(0.4)
                    : Colors.grey.withOpacity(0.3))
                  : (toolCall.isCompleted 
                    ? Colors.green.withOpacity(0.3)
                    : Colors.grey.withOpacity(0.3)),
              ),
            ),
            child: Theme(
              data: Theme.of(context).copyWith(
                dividerColor: Colors.transparent,
                expansionTileTheme: ExpansionTileThemeData(
                  tilePadding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  childrenPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
              child: ExpansionTile(
                leading: Container(
                  width: 28,
                  height: 28,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: _isMemoryTool(toolCall.name)
                      ? (toolCall.isCompleted 
                        ? Colors.purple.withOpacity(0.2) 
                        : Colors.deepPurple.withOpacity(0.2))
                      : (toolCall.isCompleted 
                        ? Colors.green.withOpacity(0.1) 
                        : Colors.orange.withOpacity(0.1)),
                  ),
                  child: Icon(
                    _getToolIcon(toolCall.name),
                    size: 16,
                    color: _isMemoryTool(toolCall.name)
                      ? (toolCall.isCompleted ? Colors.purple[600] : Colors.deepPurple[600])
                      : (toolCall.isCompleted ? Colors.green[600] : Colors.orange[600]),
                  ),
                ),
                title: Row(
                  children: [
                    Expanded(
                      child: Text(
                        _getToolDisplayName(toolCall.name),
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: isDark ? Colors.white : Colors.black87,
                        ),
                      ),
                    ),
                    if (!toolCall.isCompleted)
                      SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            _isMemoryTool(toolCall.name) 
                              ? Colors.deepPurple[600]!
                              : Colors.orange[600]!,
                          ),
                        ),
                      ),
                  ],
                ),
                subtitle: toolCall.arguments.isNotEmpty
                  ? Text(
                      _formatToolArguments(toolCall.arguments),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                  : null,
                children: [
                  if (toolCall.arguments.isNotEmpty) ...[
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(8),
                      margin: EdgeInsets.only(bottom: 8),
                      decoration: BoxDecoration(
                        color: isDark ? Colors.grey[900]!.withOpacity(0.5) : Colors.grey[100],
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '参数:',
                            style: TextStyle(
                              fontSize: 12,
                              fontWeight: FontWeight.w600,
                              color: isDark ? Colors.grey[300] : Colors.grey[700],
                            ),
                          ),
                          SizedBox(height: 4),
                          SelectableText(
                            _formatToolArguments(toolCall.arguments),
                            style: TextStyle(
                              fontSize: 11,
                              fontFamily: 'monospace',
                              color: isDark ? Colors.grey[400] : Colors.grey[600],
                              height: 1.3,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                  if (toolCall.result.isNotEmpty) ...[
                    Container(
                      width: double.infinity,
                      padding: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: _isMemoryTool(toolCall.name)
                          ? (toolCall.isCompleted 
                            ? (isDark ? Colors.purple[900]!.withOpacity(0.3) : Colors.purple[50])
                            : (isDark ? Colors.grey[900]!.withOpacity(0.5) : Colors.grey[100]))
                          : (toolCall.isCompleted 
                            ? (isDark ? Colors.green[900]!.withOpacity(0.2) : Colors.green[50])
                            : (isDark ? Colors.grey[900]!.withOpacity(0.5) : Colors.grey[100])),
                        borderRadius: BorderRadius.circular(6),
                        border: Border.all(
                          color: _isMemoryTool(toolCall.name)
                            ? (toolCall.isCompleted 
                              ? Colors.purple.withOpacity(0.4)
                              : Colors.grey.withOpacity(0.3))
                            : (toolCall.isCompleted 
                              ? Colors.green.withOpacity(0.3)
                              : Colors.grey.withOpacity(0.3)),
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(
                                toolCall.isCompleted ? Icons.check_circle : Icons.pending,
                                size: 14,
                                color: _isMemoryTool(toolCall.name)
                                  ? (toolCall.isCompleted ? Colors.purple[600] : Colors.deepPurple[600])
                                  : (toolCall.isCompleted ? Colors.green[600] : Colors.orange[600]),
                              ),
                              SizedBox(width: 4),
                              Text(
                                toolCall.isCompleted ? '执行结果:' : '执行中...',
                                style: TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.w600,
                                  color: _isMemoryTool(toolCall.name)
                                    ? (toolCall.isCompleted 
                                      ? Colors.purple[600] 
                                      : Colors.deepPurple[600])
                                    : (toolCall.isCompleted 
                                      ? Colors.green[600] 
                                      : Colors.orange[600]),
                                ),
                              ),
                            ],
                          ),
                          if (toolCall.result.isNotEmpty) ...[
                            SizedBox(height: 4),
                            SelectableText(
                              toolCall.result,
                              style: TextStyle(
                                fontSize: 11,
                                fontFamily: 'monospace',
                                color: isDark ? Colors.grey[300] : Colors.grey[700],
                                height: 1.4,
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ),
        ).toList(),
      ),
    );
  }

  /// 判断是否为记忆工具
  bool _isMemoryTool(String toolName) {
    return toolName == 'searchFromMemory' || 
           toolName == 'remember' || 
           toolName == 'getMemoryStats';
  }

  /// 获取工具图标
  IconData _getToolIcon(String toolName) {
    switch (toolName) {
      case 'searchFromMemory':
        return Icons.psychology;
      case 'remember':
        return Icons.memory;
      case 'getMemoryStats':
        return Icons.insights;
      default:
        return Icons.build;
    }
  }

  /// 获取工具显示名称
  String _getToolDisplayName(String toolName) {
    switch (toolName) {
      case 'searchFromMemory':
        return '📔 记忆搜索';
      case 'remember':
        return '📔 记忆存储';
      case 'getMemoryStats':
        return '📔 记忆统计';
      default:
        return toolName;
    }
  }

  /// 格式化工具参数显示
  String _formatToolArguments(String arguments) {
    try {
      final Map<String, dynamic> args = json.decode(arguments);
      return args.entries
          .map((entry) => '${entry.key}: ${entry.value}')
          .join('\n');
    } catch (e) {
      return arguments;
    }
  }
}

class ChatMessage {
  String text;
  final bool isUser;
  final DateTime timestamp;
  final List<ToolCallInfo> toolCalls;

  ChatMessage({
    required this.text,
    required this.isUser,
    required this.timestamp,
    this.toolCalls = const [],
  });

  Map<String, dynamic> toJson() {
    return {
      'text': text,
      'isUser': isUser,
      'timestamp': timestamp.toIso8601String(),
      'toolCalls': toolCalls.map((call) => call.toJson()).toList(),
    };
  }

  factory ChatMessage.fromJson(Map<String, dynamic> json) {
    return ChatMessage(
      text: json['text'] as String,
      isUser: json['isUser'] as bool,
      timestamp: DateTime.parse(json['timestamp'] as String),
      toolCalls: json['toolCalls'] != null 
        ? (json['toolCalls'] as List).map((item) => ToolCallInfo.fromJson(item)).toList()
        : [],
    );
  }
}

class ToolCallInfo {
  final String name;
  final String arguments;
  final String result;
  final bool isCompleted;

  ToolCallInfo({
    required this.name,
    required this.arguments,
    required this.result,
    this.isCompleted = false,
  });

  Map<String, dynamic> toJson() {
    return {
      'name': name,
      'arguments': arguments,
      'result': result,
      'isCompleted': isCompleted,
    };
  }

  factory ToolCallInfo.fromJson(Map<String, dynamic> json) {
    return ToolCallInfo(
      name: json['name'] as String,
      arguments: json['arguments'] as String,
      result: json['result'] as String,
      isCompleted: json['isCompleted'] as bool? ?? false,
    );
  }
}